package com.jastar.android.test.base.broadcast;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import androidx.core.content.ContextCompat;
import com.jastar.android.util.Alert;

public class AlarmReceiver extends BroadcastReceiver {

    public static final String ALARM_ACTION = "com.jastar.android.test.base.broadcast.alarm";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && ALARM_ACTION.equals(intent.getAction())) {
            Alert.toast(context, "接收到广播!");
        }
    }

    public void register(Context context) {
        //使用ContextCompat可以解决复杂的版本兼容性问题
        ContextCompat.registerReceiver(context, this, new IntentFilter(AlarmReceiver.ALARM_ACTION), ContextCompat.RECEIVER_NOT_EXPORTED);
    }

    public void unregister(Context context) {
        context.unregisterReceiver(this);
    }

    public void sendAlarm(Context context) {
        Intent intent = new Intent(ALARM_ACTION);

        int flags = PendingIntent.FLAG_UPDATE_CURRENT | (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : PendingIntent.FLAG_IMMUTABLE);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, flags);

        AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long triggerAtMillis = System.currentTimeMillis() + 1000;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            manager.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        } else {
            manager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
        }
    }

}
